(in-package #:org.shirakumo.fraf.trial.release)

(defun output ()
  (pathname-utils:to-directory (config :output)))

(defun version (&optional (system (config :system)))
  (or (asdf:component-version (asdf:find-system system))
      "release"))

(defun release ()
  (pathname-utils:subdirectory (output) (version)))

(defun release-version (release)
  (pathname-utils:directory-name release))

(defun update-files (&optional (target (release)))
  (loop for file in (config :build :prune)
        do (prune (merge-pathnames file target)))
  (loop for file in (config :build :copy)
        do (let ((source (merge-pathnames (if (listp file) (first file) file)
                                          (asdf:system-source-directory (config :system))))
                 (target (merge-pathnames (if (listp file) (second file) file)
                                          target)))
             (copy source target))))

(defun deploy (&key (release (release)))
  (let ((bindir (pathname-utils:subdirectory (asdf:system-source-directory (config :system)) "bin")))
    (ensure-directories-exist release)
    (deploy:copy-directory-tree bindir release :copy-root NIL)
    (update-files release)
    (org.shirakumo.filesystem-utils:ensure-deleted (merge-pathnames "trial.log" release))
    (dolist (path (list-paths release "*.exe" "*.run" "*.o" "*.dylib"))
      (let ((attrs (attributes:decode-attributes (attributes:attributes path))))
        (setf (getf attrs :other-execute) T)
        (setf (getf attrs :group-execute) T)
        (setf (getf attrs :owner-execute) T)
        (setf (attributes:attributes path) (attributes:encode-attributes attrs))))
    release))

(defun make (&key (build T) (upload T) (bundle T) (test T))
  (deploy:status 0 "Building ~a" (version))
  (build build)
  (deploy:status 1 "Testing")
  (test test)
  (deploy:status 1 "Deploying to release directory")
  (let ((release (deploy)))
    (deploy:status 1 "Creating bundles")
    (bundle bundle)
    (when upload
      (deploy:status 1 "Uploading")
      (upload upload :release release))
    release))
